<template>
	<view class="container">
		<tui-loading v-show="!pageData.loading"></tui-loading>
		<view class="page" v-show="pageData.loading" :style="{marginTop:header.init.height+'px'}">
			<tui-navigation-bar @init="initNavigation" @change="changeNavigation" :title="header.title" :color="tui.getColorSite().title.color" :backgroundColor="tui.getColorSite().title.backgroundColor" :splitLine="header.splitLine" :isOpacity="header.isOpacity" :maxOpacity="header.maxOpacity" :transparent="header.transparent" :scrollTop="header.scrollTop" :scrollRatio="header.scrollRatio" :isCustom="header.isCustom" :isImmersive="header.isImmersive" :isFixed="header.isFixed" :backdropFilter="header.backdropFilter" :dropDownHide="header.dropDownHide" :zIndex="header.zIndex">
			</tui-navigation-bar>
			<view class="tui-searchbox" :style="{top:header.init.height+'px'}">
				<view class="input">
					<tui-input clearable placeholder="请输入需要搜索的商品" type="text" confirmType="done" :size="28" isFillet padding="10rpx" v-model="param.keyword" @input="setInput" @confirm="confirmInput">
						<icon slot="left" type="search" :size='15' color='#333' style="width: 50rpx;text-align: center;"></icon>
					</tui-input>
				</view>
			</view>
			<scroll-view scroll-y scroll-with-animation class="left-box" :style="{top: pageData.classify.top + 'px',height:pageData.classify.height + 'px'}">
				<view v-for="(item, index) in pageData.classify.data" :key="index" class="tab-bar-item" :class="[pageData.classify.currentTab == index ? 'active' : '']" :data-current="index" @tap.stop="swichNav">
					<text>{{ item.name }}</text>
				</view>
			</scroll-view>
			<scroll-view scroll-y class="right-box" :scroll-top="rightBoxScrollTop" :style="{top: pageData.classify.top + 'px',height:pageData.classify.height + 'px'}" @scrolltolower="rightScrolltolower">
				<view class="tui-product-box">
					<goodsList :list="listData.data" showType="classify" @click="detail" />
					<view style="height: 120rpx;" v-if="listData.status">
						<tui-loadmore :index="3" :type="tui.getColorSite().loadmore.type" v-if="listData.xhr.status && listData.status" :text="listData.xhr.text"></tui-loadmore>
						<tui-divider width="60%" :dividerColor="tui.getColorSite().divider.dividerColor" :color="tui.getColorSite().divider.color" v-if="!listData.xhr.status && listData.status">{{ listData.xhr.text }}</tui-divider>
					</view>
				</view>
				<view class="tui-safearea-bottom"></view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import formCheck from '@/components/common/tui-validation/tui-validation.js'
	export default {
		data() {
			return {
				get: {},
				header: {
					opacity: 0,
					title: '商品分类', //NavigationBar标题
					splitLine: true, //是否需要分割线
					isOpacity: false, //是否设置不透明度
					maxOpacity: 1, //不透明度最大值 0-1
					transparent: false, //背景透明 （设置该属性，则背景透明，只出现内容，isOpacity和maxOpacity失效）
					scrollTop: 0, //滚动条滚动距离
					scrollRatio: 0.3, //isOpacity 为true时生效（opacity=scrollTop /windowWidth * scrollRatio）
					isCustom: false, //是否自定义NavigationBar内容
					isImmersive: true, //是否沉浸式,
					isFixed: true, //是否固定
					backdropFilter: false, //是否开启高斯模糊效果[仅在支持的浏览器有效果]，为true时maxOpacity设置小于1的值
					dropDownHide: false, //下拉隐藏NavigationBar，主要针对有回弹效果ios端
					zIndex: 9998, //z-index值
					init: {
						width: 0,
						height: 0,
						left: 0,
						top: 0,
						scrollH: 0,
					},
				},
				pageData: {
					loading: false,
					classify: {
						height: 0, //scroll-view高度
						top: 0,
						currentTab: 0,
						count: 0,
						data: [],
					},
					cartNum: 0,
				},
				param: {
					keyword: '',
				},
				rightBoxScrollTop: 0,
				listData: {
					notice: {
						status: false,
						text: '',
					},
					data: [],
					count: 0,
					page: 0,
					length: 0,
					isMore: false,
					xhr: {
						url: '###########',
						status: true,
						text: '正在加载...',
					},
					status: true,
				},
				appInit: {},
				user: {},
			}
		},
		// 监听页面加载，其参数为上个页面传递的数据，参数类型为 Object（用于页面传参）
		onLoad(e) {
			let that = this;
			// uni.startPullDownRefresh();
			console.log("self:onLoad++++++++++++++++++++++++++++++++++++++++++++++++++");
			uni.stopPullDownRefresh(); //停止当前页面下拉刷新
			if (typeof(e.scene) != 'undefined') {
				e = that.tui.getUrlkey(decodeURIComponent(e.scene));
			}
			that.get = e;
			if (typeof that.get.title !== 'undefined') {
				that.header.title = that.get.title;
				if (that.header.title.length > 13) {
					that.header.title = that.header.title.slice(0, 13) + '...';
				}
			}
			console.log("self:getData=>", that.get);
			let obj = {};
			// #ifdef MP-WEIXIN
			obj = wx.getMenuButtonBoundingClientRect();
			// #endif
			// #ifdef MP-BAIDU
			obj = swan.getMenuButtonBoundingClientRect();
			// #endif
			// #ifdef MP-ALIPAY
			my.hideAddToDesktopMenu();
			// #endif
			uni.getSystemInfo({
				success: function(res) {
					that.header.init.width = obj.left || res.windowWidth;
					that.header.init.height = obj.top ? obj.top + obj.height + 8 : res.statusBarHeight + 44;
					that.header.init.top = obj.top ? obj.top + (obj.height - 32) / 2 : res.statusBarHeight + 6;
					that.header.init.scrollH = res.windowWidth * 0.6;
					that.pageData.classify.height = res.windowHeight - that.header.init.height - uni.upx2px(80 + 100);
					that.pageData.classify.top = uni.upx2px(80) + that.header.init.height;
				}
			});
			that.pageData.cartNum = that.tui.getCache('goodsCartSum') || 0;
			that.listData.xhr.url = '/goods';
			that.initLoad();
		},
		// 监听页面显示。页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面
		onShow() {
			let that = this;
			console.log("self:onShow++++++++++++++++++++++++++++++++++++++++++++++++++");
			that.pageData.cartNum = that.tui.getCache('goodsCartSum') || 0;
			// #ifdef MP-WEIXIN
			if (wx.hideHomeButton) {
				wx.hideHomeButton();
			}
			uni.$once('wxGetUserPhone', function(res) {
				console.log('监听到事件来自 wxGetUserPhone', res);
				that.user = res.user;
				uni.$off('wxGetUserPhone')
			})
			// #endif
		},
		// 监听页面滚动，参数为Object
		onPageScroll(e) {
			let that = this;
			that.header.scrollTop = e.scrollTop;
			that.$forceUpdate();
		},
		methods: {
			initLoad() {
				let that = this;
				let Int = setInterval(function() {
					that.user = that.tui.getCache("user");
					console.log('self:user=>', that.user);
					if (typeof(that.user) == 'object') {
						clearInterval(Int);
						that.__init();
					}
				}, 800);
			},
			async __init() {
				let that = this;
				that.pageData.cartNum = that.user.userInfo.cartNum;
				that.tui.setCache('goodsCartSum', that.pageData.cartNum);
				that.appInit = that.tui.getCache("appInit");
				console.log('self:appInit=>', that.appInit);
				let response = '';
				response = await that.tui.get('/goods', {
					class: that.tui.formatDate().timestamp,
				});
				that.pageData.classify.data = response.data.data;
				that.pageData.classify.count = response.data.count;
				that.pageData.loading = true;
				that.listData.page = 0;
				that.initList();
			},
			// 点击标题切换当前页时改变样式
			swichNav(e) {
				let that = this;
				if (that.pageData.classify.currentTab != e.currentTarget.dataset.current) {
					that.param.keyword = '';
					that.pageData.classify.currentTab = e.currentTarget.dataset.current;
					that.listData.page = 0;
					that.initList();
				}
			},
			rightScrolltolower() { //滚动到底部/右边，会触发 scrolltolower 事件
				let that = this;
				if (that.listData.isMore == true) {
					that.listData.page++
					that.initList();
				}
			},
			detail(type, item) {
				let that = this;
				switch (type) {
					case 'goodsClick':
						that.tui.urlHref('/pages/good-info?' + that.tui.initParamsData({
							id: item.id,
							title: item.title,
						}));
						break;
					default:
						console.log(type, item);
						break;
				}
			},
			setInput(e) {
				let that = this;
				that.param.keyword = that.tui.trim(e);
				that.$forceUpdate();
			},
			confirmInput(e) {
				let that = this;
				that.param.keyword = that.tui.trim(e.detail.value);
				let rules = [
					// 
					{
						name: "keyword",
						rule: ["required", ], //可使用区间，此处主要测试功能
						msg: ["请输入搜索关键词", ]
					},
				];
				let checkRes = formCheck.validation(that.param, rules);
				if (checkRes) {
					that.tui.errorMsg(checkRes + "！")
					return;
				}
				that.listData.page = 0;
				that.initList();
			},
			async initList() {
				let that = this;
				if (that.listData.xhr.url === false) {
					that.listData.status = false;
					return;
				}
				if (that.listData.page == 0) {
					that.listData.data = [];
					that.listData.isMore = true;
					that.listData.xhr.status = true;
					that.listData.status = true;
					that.rightBoxScrollTop = 0;
				}
				let param = {
					page: that.listData.page,
					length: that.tui.requestPageLength,
					column_id: that.pageData.classify.data[that.pageData.classify.currentTab].id,
				};
				if (that.param.keyword.length > 0) {
					param.keyword = that.param.keyword;
					param.keywordKey = 'title|description';
				}
				let response = await that.tui.get(that.listData.xhr.url, param);
				switch (response.status) {
					case 0:
						response = response.data;
						// 当前分页为0的时候 返回数据为0  暂无数据
						if (response.count == 0) {
							that.listData.isMore = false;
							that.listData.xhr.status = false;
							that.listData.xhr.text = '暂无数据... ...';
						} else {
							if (that.listData.page == 0) {
								if (response.data.length < param.length) {
									that.listData.status = false;
								}
							}
							that.listData.data = that.listData.data.concat(response.data);
							if (response.data.length < param.length) {
								that.listData.isMore = false;
								that.listData.xhr.status = false;
								if (response.data.length != 0) {
									that.listData.xhr.text = '没有更多啦 ... ...';
								}
							}
						}
						break;
					default:
						that.tui.xhrReturn(response)
						that.listData.isMore = false;
						that.listData.xhr.status = false;
						that.listData.xhr.text = response.info;
						break;
				}
				that.$forceUpdate();
			},
			back() {
				let that = this;
				that.tui.urlBack(1);
			},
			initNavigation(e) {
				let that = this;
				that.header.opacity = e.opacity;
				that.header.init.top = e.top;
				that.$forceUpdate();
			},
			changeNavigation(e) {
				let that = this;
				that.header.opacity = e.opacity;
				that.$forceUpdate();
			},
		},
		// 监听页面隐藏
		onHide() {
			let that = this;
			// that.pageData.loading = false;
		},
		// 监听页面卸载
		onUnload() {
			let that = this;
		},
		// 页面返回
		onBackPress() {
			let that = this;
		},
		// #ifdef MP
		onShareAppMessage() {
			// console.log('分享!')
		},
		// #endif
	}
</script>

<style scoped lang="scss">
	.page {
		background: #fcfcfc !important;
	}

	/* 隐藏scroll-view滚动条*/
	::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
	}

	.left-box {
		// height: calc(100% - 80rpx - 20rpx - 100rpx - 60rpx);
		width: 200rpx;
		position: fixed;
		left: 0;
		z-index: 10;

		.active {
			position: relative;
			color: #000;
			font-size: 30rpx;
			font-weight: 600;
			background: #fcfcfc;

			&::before {
				content: '';
				position: absolute;
				border-left: 8rpx solid #e41f19;
				height: 110rpx;
				left: 0;
			}
		}

		.tab-bar-item {
			width: 200rpx;
			height: 110rpx;
			background: #f6f6f6;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 26rpx;
			color: #444;
			font-weight: 400;
		}
	}

	.right-box {
		width: calc(100% - 200rpx);
		position: fixed;
		right: 0;
		z-index: 10;

		.tui-product-box {
			padding: 0 20rpx 0 13rpx;
		}
	}
</style>